package com.jboost.config.redis;

import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;

import java.nio.charset.Charset;

@Slf4j
public class PrefixStringRedisSerializer implements RedisSerializer<String> {
    /**
     * 编码格式
     */
    private final Charset charset;

    /**
     * 前缀
     */
    private final String PREFIX_KEY = "sart_";

    public PrefixStringRedisSerializer() {
        this(Charset.forName("UTF8"));
    }

    public PrefixStringRedisSerializer(Charset charset) {
        this.charset = charset;
    }

    @Override
    public byte[] serialize(String s) throws SerializationException {
        String key = PREFIX_KEY + s;
        return (key == null ? null : key.getBytes(charset));
    }

    @Override
    public String deserialize(byte[] bytes) throws SerializationException {
        String saveKey = new String(bytes, charset);
        int indexOf = saveKey.indexOf(PREFIX_KEY);
        if (indexOf > 0) {
            log.error("key缺少前缀");
        } else {
            saveKey = saveKey.substring(indexOf);
        }
        return (saveKey.getBytes() == null ? null : saveKey);
    }
}
